package com.asset.service.impl;

import com.asset.mapper.AssetCategoryMapper;
import com.asset.model.vo.AssetCategoryVO;
import com.asset.service.AssetCategoryService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class AssetCategoryServiceImpl implements AssetCategoryService {

    @Resource
    private AssetCategoryMapper assetCategoryMapper;

    @Override
    public List<AssetCategoryVO> buildCategoryTree() {
        // 1. 查询所有分类数据（包含层级路径）
        List<AssetCategoryVO> allCategories = assetCategoryMapper.selectAll();

        // 2. 构建树形结构（使用HashMap提升性能）
        Map<Integer, AssetCategoryVO> nodeMap = new HashMap<>();
        List<AssetCategoryVO> rootNodes = new ArrayList<>();

        // 将所有节点存入Map（key=id）
        for (AssetCategoryVO node : allCategories) {
            nodeMap.put(node.getId(), node);
        }

        // 建立父子关系
        for (AssetCategoryVO node : allCategories) {
            Integer parentId = node.getParentTypeId();
            if (parentId == null || parentId == 0) {
                rootNodes.add(node); // 根节点
            } else {
                AssetCategoryVO parentNode = nodeMap.get(parentId);
                if (parentNode != null) {
                    parentNode.getChildren().add(node);
                }
            }
        }

        return rootNodes;
    }
}